package com.hsy.swu.version

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.hsy.swu.R
import com.hsy.swu.clouddb.LeanCloudHelper
import com.hsy.swu.hsyutils.MActivityUtil
import com.hsy.swu.spider.VariableQueryParameters
import com.kongzue.dialogx.dialogs.MessageDialog
import com.kongzue.dialogx.dialogs.PopNotification
import com.kongzue.dialogx.style.IOSStyle
import com.kongzue.dialogx.util.TextInfo

class Updater(private val mActivity: AppCompatActivity) {
    companion object {
        var currentVersionName = ""

        var remoteVersionName = ""
        var updateInfo = ""
        var apkMbSize = 0f
        var downloadUrl = ""

        var isAlreadyGetUpdateInfo = false

        private const val UPDATE_INFO_OBJECT_ID = "660c125ecd3e4b3482209aad"

        /** 从 LeanCloud 获取下载信息 */
        fun getUpdateInfoFromLeanCloud() {
            LeanCloudHelper.getInstance()?.getObjectInBackGround(
                "UpdateInfo",
                UPDATE_INFO_OBJECT_ID
            ) {
                remoteVersionName = it.get("remoteVersionName").toString()
                updateInfo = it.get("updateInfo").toString()
                apkMbSize = it.get("apkMbSize").toString().toFloat()
                downloadUrl = it.get("downloadUrl").toString()
                VariableQueryParameters.XNM = it.get("XNM").toString()
                VariableQueryParameters.XQM = it.get("XQM").toString()
                isAlreadyGetUpdateInfo = true
            }
        }
    }

    private val apkStorageFileName = "${mActivity.filesDir}/swuBBT.apk"

    private var downloadDialog: MessageDialog? = null
    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val binder = service as DownloadService.DownloadBinder
            binder.getService().setDownloadProgressListener {
                when (it) {
                    100 -> {
                        mActivity.unbindService(this)
                        downloadDialog?.dismiss()
                        downloadDialog = null
                    }

                    -1 -> {
                        PopNotification.build()
                            .setTitle("下载失败，请重试")
                            .noAutoDismiss()
                            .setBackgroundColorRes(R.color.blackGray)
                            .setTitleTextInfo(TextInfo().apply {
                                fontColor =
                                    ContextCompat.getColor(mActivity, R.color.white)
                            })
                            .show()
                        mActivity.finish()
                    }

                    else -> {
                        if (downloadDialog == null) {
                            downloadDialog = MessageDialog.build()
                                .setTitle("正在下载...")
                                .setMessage("0 %")
                                .setOkButton("隐藏进度显示") { _, _ ->
                                    MActivityUtil.showToast("下载完成将跳转安装")
                                    return@setOkButton false
                                }
                                .show()
                        }
                        downloadDialog?.setMessage("$it %")
                    }
                }
            }
        }

        override fun onServiceDisconnected(name: ComponentName?) {
        }
    }

    /** 检查是否需要更新 */
    fun checkIsNeedUpdate(): Boolean {
        if (!isAlreadyGetUpdateInfo) return false

        currentVersionName =
            mActivity.packageManager.getPackageInfo(mActivity.packageName, 0).versionName

        return currentVersionName != remoteVersionName
    }

    /** 显示更新的 Dialog */
    fun showUpdateDialog(isPostNotification: Boolean) {
        var messageText = ""
        updateInfo.split("|").forEach {
            messageText += "👉 $it\n"
        }

        val messageDialog = MessageDialog.build()
            .setTitle("新版本")
            .setMessage("version_$remoteVersionName\n\n$messageText")
            .setOkButton("立即更新") { _, _ ->
                val downloadIntent = Intent(mActivity, DownloadService::class.java)
                    .putExtra("downloadSize", apkMbSize)
                    .putExtra("downloadUrl", downloadUrl)
                    .putExtra("storageFileName", apkStorageFileName)

                mActivity.bindService(downloadIntent, serviceConnection, Context.BIND_AUTO_CREATE)
                return@setOkButton false
            }

        val textInfo = TextInfo().apply {
            fontColor = ContextCompat.getColor(mActivity, R.color.white)
        }
        if (isPostNotification) {
            PopNotification.build()
                .setStyle(IOSStyle())
                .setTitle("新版本")
//                .setTitleTextInfo(textInfo)
                .setMessage("${updateInfo.split("|").first()} ......")
//                .setMessageTextInfo(textInfo)
//                .setIcon(ContextCompat.getDrawable(mActivity, R.drawable.left_drawer_ic_renew))
                .setButton("立即更新") { _, _ ->
                    messageDialog.show()
                    return@setButton true
                }
                .setButtonTextInfo(TextInfo().apply {
                    fontColor = ContextCompat.getColor(mActivity, R.color.lightBlue)
                })
//                .setBackgroundColorRes(R.color.blackGray)
                .autoDismiss(2000)
                .show()
        } else {
            messageDialog.show()
        }
    }
}